package com.atguigu.gulimall.member.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

//每一次feign发起request请求时都要拦截，
// 将老的cookies同步到feign创建的新的的request的header中去
//RequestContextHolder也是一个ThreadLocal
@Configuration
public class GuliFeignConfig {

       @Bean("requestInterceptor")
       public RequestInterceptor requestInterceptor(){
              //再请求发送的时候拦截，要处理cookie丢失问题，将老请求中的cookie放到新请求中去
              return new RequestInterceptor() {
                     @Override
                     public void apply(RequestTemplate requestTemplate) {

                            System.out.println("RequestInterceptor线程"+Thread.currentThread().getId());
                            //requestContextHolder拿到刚进来的请求
                            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                            if (attributes != null) {
                                   //需要共享数据的线程就给attributes，不需要就不给就好了
                                   HttpServletRequest request = attributes.getRequest();
                                   //这个要给feign加上请求头，不然feign默认使用空的request，就拿不到用户的信息
                                   // cookie中有 user-key 和 GULISESSION，谷粒session中包含用户的所有信息
                                   // 同步cookie,拿到老请求中的cookie，放到新请求里面去
                                   if (request != null) {
                                          String cookie = request.getHeader("Cookie");
                                          requestTemplate.header("Cookie",cookie);
                                   }
                            }
                     }
              };

       }
}
